const Service = require('../../../core/service/ApiService');

class ItemDao extends Service {

    //搜索服务项目
    async searchItemId(name) {
        return this.model.ServiceItem.findOne({
            where: {
                name: name,
                status: this.constant.SVC_ITEM_STATUS.ENABLE
            },
            attributes: ['svc_item_id', 'name'],
            raw: true
        })
    }

    //搜索服务次数
    async searchAmount(svc_item_id, date) {
        const sql = `select count(*) as cnt from service_record
                    where date_sub(curdate(),INTERVAL 30 DAY) <='${date}'
                    and service_record.status not in (${this.constant.SVC_STATUS.EXCEPTION})
                    and svc_item_list like '%${svc_item_id}%'`;
        const svc = await this.model.query(sql, {type: this.model.QueryTypes.SELECT});
        return svc === 0 ? null : svc[0].cnt;
    }

    //编辑服务项目
    async editItem(id, name) {
        this.model.ServiceItem.update({
            name: name
        }, {
            where: {
                svc_item_id: id
            }
        })
    }

    //删除服务项目
    async delete(id) {
        this.model.ServiceItem.update({
            status: this.constant.SVC_ITEM_STATUS.DISABLE
        }, {
            where: {
                svc_item_id: id
            }
        })
    }

    //添加服务项目
    async addItem(name) {
        return this.model.ServiceItem.create({
            name: name
        })
    }

    //服务项目查看统计
    async viewStatistic(id, date) {
        const sql = `select count(*) as svc_cnt,date_format(service_record.end_time,'%m-%d') as date
                    from service_record
                    where service_record.svc_item_list like '%${id},%'
                    and date_sub(curdate(),interval 1 month)<= '${date}'
                    and service_record.status not in (${this.constant.SVC_STATUS.EXCEPTION})
                    group by date
                    order by date desc`;
        const result = await this.model.query(sql, {type: this.model.QueryTypes.SELECT});
        return result.length === 0 ? null : result;
    }


}

module.exports = ItemDao;
